package com.yswy.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.app.service.SysConfigService;
import com.yswy.app.service.ZfbPayKeyService;
import com.yswy.common.enums.PayMethodEnums;
import com.yswy.common.utils.DateUtils;
import com.yswy.common.utils.dingding.DingUtil;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.common.zfbOrder.ZfbKeyVo;
import com.yswy.domain.entity.PayOrderZfbLog;
import com.yswy.domain.entity.ZfbPayKey;
import com.yswy.domain.mapper.ZfbPayKeyMapper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ZfbPayKeyServiceImpl extends ServiceImpl<ZfbPayKeyMapper, ZfbPayKey>
        implements ZfbPayKeyService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DingUtil dingUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZfbKeyVo cutAppId(String payMethod) {
        //查询当前已使用账号
        ZfbPayKey zfbPayKey =  (ZfbPayKey) redisUtil.getObejct(payMethod);
        if (zfbPayKey != null){
            boolean isCash = cashAppId(zfbPayKey ,payMethod );
            if (isCash){
                zfbPayKey = null ;
            }
        }
        if (zfbPayKey == null){
            LambdaQueryWrapper<ZfbPayKey> lambdaQueryWrapper = new LambdaQueryWrapper<ZfbPayKey>();
            lambdaQueryWrapper.in(ZfbPayKey::getKeyStatus , 0 , 1).orderByAsc(ZfbPayKey::getLastUsdTime);
            if (payMethod.equals(PayMethodEnums.PT_ZFB_USED.getMessage())){
                lambdaQueryWrapper.eq(ZfbPayKey::getOpenAppPay , true);
            }else if (payMethod.equals(PayMethodEnums.WEB_ZFB_USED.getMessage())){
                lambdaQueryWrapper.eq(ZfbPayKey::getOpenH5Pay , true);
            }else if (payMethod.equals(PayMethodEnums.ZQFK_ZFB_USED.getMessage())){
                lambdaQueryWrapper.eq(ZfbPayKey::getOpenTradePay , true);
            }else if (payMethod.equals(PayMethodEnums.TX_ZFB_USED.getMessage())){
                lambdaQueryWrapper.eq(ZfbPayKey::getOpenWithdrawal , true);
            }
            List<ZfbPayKey> zfbPayKeys  = list(lambdaQueryWrapper);
            if (zfbPayKeys.size() <= 0 ){
                dingUtil.sendMsg(payMethod+"(紧急)支付宝预警公告：\n暂无可用支付宝账号，" +
                        "检测时间"+ DateUtils.getTime() +"，请管理员及时登陆处理。");
                throw new IllegalArgumentException("支付失败，请联系客服");

            }else {
                zfbPayKey = zfbPayKeys.get(0);
                zfbPayKey.setKeyStatus(1);
                zfbPayKey.setLastUsdTime(new Date());
                updateById(zfbPayKey);
                dingUtil.sendMsg(payMethod + "支付宝切换公告：\n当前使用支付宝"+zfbPayKey.getEMail());
                redisUtil.setForObjectTimeCustom(payMethod , zfbPayKey,zfbPayKey.getBigTime(), TimeUnit.MINUTES);
            }
        }
        ZfbKeyVo zfbKeyVo  = getZfbKeyVo(null , zfbPayKey);

        return zfbKeyVo ;
    }

    @Override
    public boolean cashAppId(ZfbPayKey zfbPayKey ,String payMethod ) {
        //判断收款金额是否上限
        //查询其余平台收款金额
        if (redisUtil.hasKey(RedisConstants.ZFB_MONEY_APPID+zfbPayKey.getAppId())){
            Integer payMoney = Integer.parseInt(redisUtil.get(RedisConstants.ZFB_MONEY_APPID+zfbPayKey.getAppId()));
            if (payMoney >= zfbPayKey.getMaxMoney() ){
                dingUtil.sendMsg("支付宝预警公告：\n支付宝账号"
                        +zfbPayKey.getEMail()+"收款达到当日上限 +"+
                        "，检测时间"+
                        DateUtils.getTime() +"，请管理员及时登陆处理。");
                redisUtil.delete(payMethod);
                zfbPayKey.setKeyStatus(3);
                updateById(zfbPayKey);
                return true;
            }
        }

        return false ;
    }

    @Override
    public void recordPayMoney(Integer amount, String appId) {
        Integer getAmount = amount /100 ;
        if (redisUtil.hasKey(RedisConstants.ZFB_MONEY_APPID+appId)){
            Integer d = Integer.parseInt(
                    redisUtil.get(RedisConstants.ZFB_MONEY_APPID+appId))
                    +getAmount ;
            redisUtil.set(RedisConstants.ZFB_MONEY_APPID+appId
                    ,d.toString());
        }else {
            redisUtil.set(RedisConstants.ZFB_MONEY_APPID+appId
                    ,getAmount.toString());
        }
    }

    @Override
    public ZfbKeyVo getZfbKeyVo(Long id ,ZfbPayKey zfbPayKey ) {
        if (zfbPayKey == null){
            zfbPayKey = getById(id);
        }
        ZfbKeyVo zfbKeyVo = new ZfbKeyVo();
        zfbKeyVo.setId(zfbPayKey.getId());
        zfbKeyVo.setZfbKey(zfbPayKey.getZfbKey());
        zfbKeyVo.setAppId(zfbPayKey.getAppId());
        zfbKeyVo.setJavaKey(zfbPayKey.getJavaKey());
        zfbKeyVo.setProductCode(zfbPayKey.getProductCode());
        zfbKeyVo.setCertPath(zfbPayKey.getCertPath());
        zfbKeyVo.setRootCertPath(zfbPayKey.getRootCertPath());
        zfbKeyVo.setPublicCertPath(zfbPayKey.getPublicCertPath());
        zfbKeyVo.setSingType(zfbPayKey.getSingType());
        return zfbKeyVo;
    }

    @Override
    public ZfbKeyVo getZfbKeyVo(PayOrderZfbLog payOrderZfbLog) {
        ZfbKeyVo zfbKeyVo = new ZfbKeyVo();
        zfbKeyVo.setZfbKey(payOrderZfbLog.getPublicKey());
        zfbKeyVo.setAppId(payOrderZfbLog.getAppId());
        zfbKeyVo.setJavaKey(payOrderZfbLog.getPrivateKey());
        zfbKeyVo.setProductCode(payOrderZfbLog.getProductCode());
        zfbKeyVo.setCertPath(payOrderZfbLog.getCertPath());
        zfbKeyVo.setRootCertPath(payOrderZfbLog.getRootCertPath());
        zfbKeyVo.setPublicCertPath(payOrderZfbLog.getPublicCertPath());
        zfbKeyVo.setSingType(payOrderZfbLog.getSingType());
        return zfbKeyVo;
    }

}
